﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.ComponentModel;
using System.Globalization;

namespace MvcImproved.Generic.Controls
{
	public class Radio<TDataItem, TMemberValue> : GenericInputControl<TDataItem, TMemberValue>
	{
		public Radio(Func<TDataItem, TMemberValue> valueMember)
			: base(valueMember, "radio")
		{
			RenderChildrenFirst = false;
		}

		public TMemberValue Value
		{
			get;
			set;
		}

		public string Text
		{
			get { return Label; }
			set { Label = value; }
		}

		protected override void ControlSpecificRender(HtmlTextWriter writer, SortedDictionary<string, string> attrs)
		{
			if (!DesignMode)
			{
				// Use an explicit value attribute if it is available. Otherwise get it from ViewData.
				TMemberValue objectValue = ValueMemberLambda(DataValue);

				// The HtmlTextWriter will automatically encode this value
				if (EqualityComparer<TMemberValue>.Default.Equals(Value, objectValue))
					attrs.Add("checked", "checked");
			}
			attrs["value"] = (Value != null) ? Value.ToString() : "";
		}
	}

	// Non-generic version of the control that's used in the actual markup
	[ControlBuilder(typeof(GenericControlBuilder))]
	[GenericControlType(typeof(Radio<,>), MemberValue = "ValueMember", GenericParameters = "ModelType")]
	public class Radio : Radio<object, object>
	{
		public Radio()
			: base(null)
		{ }

		public string ModelType
		{
			get;
			set;
		}
	}
}
